<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
		<title>虎扑跑步限时闪购</title>
		<link rel="stylesheet" type="text/css" media="screen" href="{$staticHost}/static/css/base.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="{$staticHost}/static/css/page.css" />
		<script src="{$staticHost}/static/js/js.js"></script>
		<script src="{$staticHost}/static/js/mod.js"></script>
	</head>
	<body>
		<div class="f-flash-container">
            <div class='f-flash-banner'>
                <img class='banner-shop ck-bigImg' src=''>
                <div class='renderPrice'></div>
            </div>

            <div class='renderList'></div>
            <div class='f-imageData renderImageDate'></div>

            <p class='f-flash-buy ck-buy'>购买</p>

			<div class='renderRule'></div>

            <!-- 遮罩 -->
            <div class='f-flash-cover'></div>

		</div>

		<script src="{$staticHost}/static/js/react.min.js"></script>
		<script src="{$staticHost}/static/js/react-dom.min.js"></script>
		<script src="{$staticHost}/static/js/browser.min.js"></script>
		<script src="{$staticHost}/static/js/jquery-3.1.0.min.js"></script>
		<script src=" https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

        <script type='text/babel'>


			// react渲染頁面
			var data = {};
			var obj = {};
			var loadData = false;
			var sup = typeof jw === "object";
			sup = true;
			var aid = 0;

			var flashId = "{$saleId}";

			// JQuery ajax 调接口，获取数据
			$.ajax({
				type: 'GET',
				url: '{$staticHost}/flashBuyWeb/getFlashDetail?flashId='+flashId,

				data: {},
				dataType: 'json',
				success: function(data){

					$(".banner-shop").attr("src",data.result.list.imageUrl )
					loadData = true;
					data = data;
					aid = data.result.list.id;
					obj = data.result.list.goodList[0];
					var ruleTitle = [];
					for(var i = 0; i < obj.attrs.length; i++){
						ruleTitle.push(obj.attrs[i].headInfo.title);
					}

					var currentTime = parseInt(data.result.list.currentTime);
					// var currentTime = 1476158439;

					var startTime = parseInt(data.result.list.startTime);


					var endTime = parseInt(data.result.list.endTime);
					var tempTime = endTime - currentTime;
					var d = new Date(parseInt(startTime) * 1000);
					var timeStart =xs(d.getMonth()+1)+"月"+xs(d.getDate())+ "日"+xs( d.getHours())+":"+xs(d.getMinutes());
					function xs(n){ 
						return n<10?("0"+n):n;
					}

					var shopInfo = {
						costPrice: data.result.list.costPrice,
						leftTime: '',
						shopTitle: data.result.list.title
					};

					setInterval(function(){
						currentTime++;
						tempTime = endTime - currentTime;
						
					    var d=Math.floor(tempTime/60/60/24);
					    var h=Math.floor(tempTime/60/60%24);
					    var m=Math.floor(tempTime/60%60);
					    var s=tempTime-d*24*3600-h*3600-m*60
						var leftTime = d+"日"+' '+h+':'+m+':'+s;

						if(currentTime > startTime && currentTime < endTime){
							shopInfo.leftTime = leftTime;
						}else if(currentTime > endTime){
							shopInfo.leftTime = '活动已结束';
							if(sup){
								$('.f-flash-buy').html('活动已结束');
								$('.f-flash-buy').css('background', '#ADADB3');
								$('.f-flash-buy').unbind();
							}
						}else if(currentTime < startTime){
							$('.f-state').html('开始时间');
							if(sup){
								$('.f-flash-buy').html('敬请期待');
								$('.f-flash-buy').css('background', '#1F8EE5');
							}
							shopInfo.leftTime =timeStart
						
						}

					}, 1000);

				  
					// 顶部导航图片
					if(currentTime < data.result.list.startTime){
						shopInfo.discountPrice = '?';
					}
					var RenderPrice = React.createClass({
						render: function(){
							return (
								<div className='f-shop-price'  data-time={new Date()}>
									<p><span>¥{shopInfo.discountPrice}</span><span>专柜价:￥{shopInfo.costPrice}</span></p>
									<p><span className='f-state'>剩余时间</span><span>{shopInfo.leftTime}</span></p>
									<div className="clear"></div>
									<p className='f-flash-title'>{shopInfo.shopTitle}</p>
								</div>
							);
						}


					});

					setInterval(function(){
						ReactDOM.render(
							<RenderPrice />,
							document.querySelector('.renderPrice')
						);
					}, 1000);

					var goodList = data.result.list.goodList[0];

					var shopList = [
						{
							title: data.result.list.goodList[0].product.title,
						}
					];


					var RenderList = React.createClass({
						render: function(){
							return (
								<div className='f-flash-shop'>
									<ul>
										<li>产品信息</li>
									</ul>
								</div>
							);
						}
					});

					ReactDOM.render(
						<RenderList />,
						document.querySelector('.renderList')
					);
					var mixinData = data.result.list.imageContent;
					$('.renderImageDate').html(mixinData);

					var allRules = [];
					for(var m = 0; m < obj.childGoods.length; m++){
						for(var n = 0; n < obj.childGoods[m].attr.length; n++){
							allRules.push(obj.childGoods[m].attr[n].name);
						}
					}

					var shopRule = obj.attrs;

					var RenderRule = React.createClass({
						render: function(){
							return (
								<div className='f-flash-rule'>
									<span className='f-flash-close ck-close'>×</span>
									{Array.isArray(shopRule) && shopRule.map(function(item){
										return(
											<dl>
												<dt>{item.headInfo.title}</dt>
												{Array.isArray(item.attrValue) && item.attrValue.map(function(subitem){
													return (
														<dd data-aid={subitem.id}>
															<span>{subitem.title}</span>
														</dd>
													);
												})}
											</dl>
										);
									})}
									<p><span>价格: <strong><em className='price-number'>-</em></strong></span><span className='ck-sure bg_gray'>确定</span></p>
								</div>
							);
						}
					});

					ReactDOM.render(
						<RenderRule />,
						document.querySelector('.renderRule')
					);

					var x;
					var i;
					var minValue =[];
					var priceInfo = data.result.list.goodList
					for(x in priceInfo){
						for(i in priceInfo[x].childGoods){
							var priceMin = priceInfo[x].childGoods[i].saleprice
							minValue.push(priceMin)
						}
					}
					shopInfo.discountPrice=Math.min.apply(null, minValue)
					//获取商品最小价格
					
					


					/* js文件 */
					var buy = document.querySelector('.ck-buy');
					var shopping = document.querySelector('.ck-shopping');
					var cover = document.querySelector('.f-flash-cover');
					var close = document.querySelector('.ck-close');
					var rule = document.querySelector('.f-flash-rule');
					var sure = document.querySelector('.ck-sure');
					var dl = document.querySelectorAll('dl');
					var dd = document.querySelectorAll('dd');
					var priceNumber = document.querySelector('.price-number');
					$(function(){
				      if(typeof jw === "object") {
				        jw.api('share_button', JSON.stringify({'status': true}));
				        jw.api('set_share_info', JSON.stringify({
				          'title': '虎扑跑步限时闪购',
				          'description': data.result.list.title,
				          'img_url': data.result.list.imageUrl,
				          'link_url':'{$staticHost}/show/flashSales?saleId='+flashId,
				        }));
				      }
				   });
		   
					function submitClick(){
						$(function(){
							if(!sup) {
							    alert('请到app内分享...');
							    $("#title").append("<div><h5>不支持分享jw.api | type:" + (typeof jw) + "</h5></div>");
						    }else{

								jw.api('share', JSON.stringify({'channel': 'weixin_side'}));
							}
					    });

					}
					if (browser.versions.mobile) {
				        var ua = navigator.userAgent.toLowerCase();
				        if (ua.match(/MicroMessenger/i) == "micromessenger") {
							WeixinApi.ready(function(Api){
							 
							    // 微信分享的数据
							    var wxData = {
							        "imgUrl":data.result.list.imageUrl,
							        "link":'{$staticHost}/show/flashSales?saleId='+flashId,
							        "desc":data.result.list.title,
							        "title":"虎扑跑步限时闪购"
							    };
							 	Api.shareToFriend(wxData, wxCallbacks);
							 
							    Api.shareToTimeline(wxData, wxCallbacks);
							 
							});
						}
					}
					// 分享所需JS

					function coverNone(){
						cover.style.display = 'none';
						rule.style.display = 'none';
					}

					// 点击购买
					buy.onclick = function(event){
					if(sup){
						if(currentTime < startTime){
							return
						}else if(currentTime > endTime){

							return
						}
						cover.style.display = 'block';
						rule.style.display = 'block';
						$('.f-cover-img').hide();

						}else{
							return
						}
				}
					// 点击图片显示大图
					$('.ck-bigImg').click(function(event){
						cover.innerHTML = '<img class="' + event.target.className +  ' f-cover-img" src=' + event.target.src + '>';
						cover.style.display = 'block';
						$('body').bind('touchmove', function(event){
							event.preventDefault();
						});
						$('body').bind('mousewheel', function(event){
							return false;
						});
					});

					// 点击关闭按钮隐藏规格框
					close.onclick = function(event){
						coverNone();
					}

					// 点击遮罩隐藏
					cover.onclick = function(event){
						coverNone();
						$('body').unbind('touchmove');
						$('body').unbind('mousewheel');
					}
					
					var goodRoutes = {},
						goodAttrs = {},
						goodId = 0;
					var cn = 'f-same-blue',
						cnb = 'bg_gray',
						ruleCount = $('.f-flash-rule dl').length;

					converGoodsAttr(obj.childGoods);

					// 规格点击
					$('.f-flash-rule dl dd').click(function(){
						var thisAid = $(this).attr('data-aid');
						var gl = $('.f-flash-rule dl').length;
						
						// 变更规格按钮样式
						if($(this).hasClass(cn)) {
							removeBgBlue(this);
						} else if($(this).hasClass(cnb)) {
							return;
						} else {
							$(this).parent().find('dd').each(function(){removeBgBlue(this)});
							addBgBlue(this);
						}

						var onObj = $('.f-flash-rule dl dd.' + cn),
							onCount = onObj.length,
							onAids = [],
							onRule = '';
						var allObj = $('.f-flash-rule dl dd');
						var canAids = [];

						onObj.each(function(){onAids.push($(this).attr('data-aid'))});

						if(onCount > 0) {
							allObj.each(function(){
								if(!$(this).hasClass(cnb)) {
									addBgGray(this);
								}
							});
						} else {
							allObj.removeClass(cn).removeClass(cnb);
						}

						// 过滤
						for(var i = 0; i < onAids.length; i ++) {
							if(goodRoutes[onAids[i]] != undefined) {
								for(var j in goodRoutes[onAids[i]]) {
									var can = true;
									for(var n = 0; n < onAids.length; n ++) {
										if(can) {
											can = goodRoutes[onAids[i]][j].indexOf(onAids[n]) > -1;
										}
									}
									if(can) {
										var tmp = goodRoutes[onAids[i]][j].split(',');
										for(var l in tmp) {
											if(canAids[tmp[l]] == undefined) {
												canAids[tmp[l]] = 1;
											} else {
												canAids[tmp[l]]++;
											}
										}
									}
								}
							}
						}
						for(var m in canAids) {
							if(canAids[m] > (onCount == 1 ? 0 : onCount - 1)) {
								removeBgGray($('.f-flash-rule dl dd[data-aid=' + m + ']'));
							}
						}

						if(gl == 1) {
						    allObj.each(function(){removeBgGray(this);});
						}

						// 设置购买信息
						if(onCount == ruleCount) {
							onRule = onAids.join(',');

							if(goodAttrs[onRule] != undefined) {
								goodId = goodAttrs[onRule].goodId;
								setSubmit(goodAttrs[onRule].price);
							} else {
								resetSubmit();
							}
						} else {
							resetSubmit();
						}
					});

					// 加蓝
					function addBgBlue(obj) {
						if(!$(obj).hasClass(cnb) && !$(obj).hasClass(cn)) {
							$(obj).addClass(cn);
						}
					}

					// 加灰
					function addBgGray(obj) {
						if(!$(obj).hasClass(cn) && !$(obj).hasClass(cnb)) {
							$(obj).addClass(cnb);
						}
					}

					// 去蓝
					function removeBgBlue(obj) {
						$(obj).removeClass(cn);
					}

					// 去灰
					function removeBgGray(obj) {
						$(obj).removeClass(cnb);
					}

					// 确认设置
					function setSubmit(price) {
						$('.price-number').text('￥' + price);
						$('.ck-sure').addClass('bg_blue');
						$('.ck-sure').removeClass('bg_gray');
					}

					// 确认重置
					function resetSubmit() {
						goodId = 0;
						$('.price-number').text('-');
						$('.ck-sure').removeClass('bg_blue');
						$('.ck-sure').addClass('bg_gray');
					}

					// 转换商品规格
					function converGoodsAttr(attrs) {
						for(var i in attrs) {
							var routes = [], routesStr = '';
							for(var j in attrs[i].attr) {
								routes.push(attrs[i].attr[j].id);
							}
							routesStr = routes.join(',');
							goodAttrs[routesStr] = {
								'routes': routes,
								'name': attrs[i].attrPathName,
								'goodId': attrs[i].id,
								'stock': attrs[i].stockNum * 1,
								'price': attrs[i].saleprice,
							};
							for(var k in routes) {
								if(goodRoutes[routes[k]] == undefined) {
									goodRoutes[routes[k]] = [];
								}
								goodRoutes[routes[k]].push(routesStr);
							}
						}
					}

					// 点击确定按钮购买商品
					sure.onclick = function(event){
					console.log($('.price-number').text(), goodId);
						if(parseFloat($('.price-number').text().replace('￥', '')) > 0 && goodId > 0){
							window.location = 'joggers://order/goodsDetail?atype=flashSales&goods_id='+goodId+'&aid='+aid;
						}else{
						}
						return;
						coverNone();
					}

				}

			});
			 if(!sup) {
			   $(".f-flash-buy").html("下载虎扑跑步APP参加 精彩活动");
			   $('.f-flash-buy').css('background', '#1F8EE5');
			   $('.f-flash-buy').click(function(){
			   		 window.location.href='http://mobile.hupu.com/download/joggers?r=share';
			   })
			  
		    }
			

		</script>

	</body>
{template 'show/web-footer'}